const inquirer = require('inquirer')
const path = require('path')
const fs = require('fs')
const config = require('./config')

const prompts = [
  {
    type: 'list',
    name: 'activityType',
    message: 'Please choose type:',
    default: config.activityMap[0],
    choices: ['game', 'h5']
  },
  {
    type: 'input',
    name: 'activityName',
    message: 'please input your project name:',
    default: config.activityName
  },
  {
    type: 'confirm',
    name: 'activityReadme',
    message: 'please confirm need readme? yes or no',
    default: true
  }
]

let Generator = function(){
  this.activity_type = Object.keys(config.activityMap)  //创建一个自己的可枚举的对象的属性名称的数组
  this.props = '';
  this.chooseDir = '';
  this.chooseName = '';
  this.prompting().then( (data) => {
    return this.writing(data)
  })
  
}

// 这个情况可以使用 Generator
// ES6 Generator
// ES7 await async
Generator.prototype = {
  constructors: Generator,  
  prompting() {
    let promise = new Promise(function (resolve, reject) {
      inquirer.prompt(prompts).then(props => {
        this.props = props
        console.log('this.props:', this.props)
        setTimeout(() => {        
          resolve(this.props);
        }, 1000);
      })
    })
    return promise
  },
  writing(data){
    this.chooseDir = config.activityMap[data.activityType] || Object.keys(config.activityMap)[0];
    console.log('this.chooseDir:', data, this.chooseDir, data.activityName)
    let frompath = path.join(path.resolve(__dirname), './templates/Engineering')
    let topath = path.resolve(__dirname, '../' + data.activityName)
   
    copyfile_promise(frompath, topath).then((promise_data) => {
      console.log('data.activityName==', data.activityName)
      copyfile_promise(path.resolve(__dirname, './templates/activity/' + this.chooseDir), path.resolve(__dirname, '../' + data.activityName + '/src'))
    })

    if (data.activityReadme) {      
      config.writefile(topath, 'test.txt', 'readme.md')
    }

    console.log('writing:',data)
  }
}

function copyfile_promise(from, to){
  let copy_promise = new Promise(function(resolve, reject) {
    config.exists(from, to, config.copyfile)
    resolve('success');
  })
  return copy_promise
}

new Generator()
